package com.yzc.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yzc.result.Result;
import com.yzc.result.ResultCodeEnum;
import com.yzc.util.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
public class MdcFilter implements Filter {
    private final JwtUtil jwtUtil;

//    @Autowired
    public MdcFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        try {
            String authHeader = httpRequest.getHeader("Authorization");
            if (StringUtils.hasText(authHeader) && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                Result<Void> voidResult = jwtUtil.validateToken(token);
                if (voidResult.getCode() == Result.success().getCode()) {
                    // 提取用户信息并存储
                    Long userId = jwtUtil.extractUserId(token);
                    String username = jwtUtil.extractUsername(token);
                    MDC.put("userId", userId.toString());
                    MDC.put("username", username);
                } else {
                    // 直接返回JSON错误
                    httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
                    httpResponse.setContentType("application/json");
                    new ObjectMapper().writeValue(
                            httpResponse.getWriter(),
                            Result.fail(ResultCodeEnum.INVALID_TOKEN)
                    );
                    return;
                }
            }
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("MdcFilter异常", e);
            httpResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            httpResponse.setContentType("application/json");
            new ObjectMapper().writeValue(
                    httpResponse.getWriter(),
                    Result.fail(ResultCodeEnum.SYSTEM_ERROR)
            );
        } finally {
            MDC.clear();
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
